import React, { useEffect, useState } from 'react'
import axios from 'axios'

import PubSub from 'pubsub-js'

export default function Header() {

  // 使用受控组件获取 input 的值
  const [search, setSearch] = useState('')
  const iptChangeHandler = (e) => {
    setSearch(e.target.value)
  }

  useEffect(() => {
    // 发布初始数据
    PubSub.publish('github', {init: true, search: true, data: []})
  }, [])

  // 点击 Search 按钮，发送 axios 请求
  const searchBtnHandler = async () => {
    // 发布初始数据
    PubSub.publish('github', {init: false, search: true, data: []})
    try {
      const result = await axios.get(`https://api.github.com/search/users?q=${search}`)
      // 发布（通过 PubSub 将数据传给兄弟组件 List）
      PubSub.publish('github', {init: false, search: false, data: result.data.items})
    } catch (error) {
      alert(error)
    }
  }

  return (
    <section className="jumbotron">
      <h3 className="jumbotron-heading">Search Github Users</h3>
      <div>
        <input
          type="text"
          placeholder="enter the name you search"
          value={search}
          onChange={iptChangeHandler}
        />&nbsp;
        <button onClick={searchBtnHandler}>Search</button>
      </div>
    </section>
  )
}
